package com.baseweb.webadmin.controller.web;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.BaseState;
import com.baseweb.webadmin.core.constants.Constants;
import com.baseweb.webadmin.core.model.bvo.UserForm;
import com.baseweb.webadmin.core.model.pojo.User;
import com.baseweb.webadmin.core.util.CheckCodeUtil;
import com.baseweb.webadmin.core.util.CommonUtil;
import com.baseweb.webadmin.core.util.ConfigUtil;
import com.baseweb.webadmin.core.util.MD5Util;
import com.baseweb.webadmin.extshiro.ZheUsernamePasswordToken;
import com.baseweb.webadmin.extshiro.factoryBean.AdShiroFilterFactoryBean;
import com.baseweb.webadmin.service.*;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by dengsy on 2017-06-22.
 * 登录登出
 */
@Controller
@RequestMapping(value = "/loginWeb")
public class LoginWebController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(com.baseweb.webadmin.controller.admin.LoginController.class);
    private final static String SESSION_CHECK_CODE = "checkCode";

    @Autowired
    private UserService userService;

    /**
     * 登出
     */
    @RequestMapping(value = "/unLogin" , method = RequestMethod.GET)
    public String unLogin(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        session.setAttribute("is_login", false);
        session.removeAttribute("login_name");
        session.removeAttribute("login_id");
        session.removeAttribute("login_type");
        return "";
    }

    /**
     * 判断是否登录
     */
    @RequestMapping(value = "/isLogin" , method = RequestMethod.GET)
    public String isLogin(HttpServletRequest request,Model model){
        String isLogin = "NO";
        HttpSession session = request.getSession();
        if(session.getAttribute("login_name") != null){
            String userName = String.valueOf(session.getAttribute("login_name"));
            User user = userService.findUserByUserName(userName);
            isLogin = "OK";
            model.addAttribute("userName", userName);
            model.addAttribute("userId", String.valueOf(session.getAttribute("login_id")));
            model.addAttribute("userType", String.valueOf(session.getAttribute("login_type")));
            model.addAttribute("province", String.valueOf(session.getAttribute("login_province")));
            model.addAttribute("city", String.valueOf(session.getAttribute("login_city")));
            model.addAttribute("area", String.valueOf(session.getAttribute("login_area")));
            model.addAttribute("bizDealCount", user.getBizDealCount());
            model.addAttribute("bizYdCount", user.getBizYdCount());
            model.addAttribute("money", user.getMoney());
        }
        model.addAttribute("isLogin", isLogin);
        return "";
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "/editPassWord" , method = RequestMethod.POST)
    public String editPassWord(HttpServletRequest request,@ModelAttribute()UserForm userForm, Model model){
        String isOK = "NO";
        HttpSession session = request.getSession();
        if(userForm.getUsername() == null || "".equals(userForm.getUsername())){
            if(session.getAttribute("login_name") != null){
                String userName = String.valueOf(session.getAttribute("login_name"));
                String passWord = MD5Util.Md5(userForm.getPassword());
                User user = userService.findUserByNamePassWord(userName,passWord);
                if(user != null){
                    user.setPassword(MD5Util.Md5(userForm.getPasswordNew()));
                    if(userService.updateUser(user) == 1){
                        isOK = "OK";
                    }else {
                        model.addAttribute("msg", "修改失败");
                    }
                }else {
                    model.addAttribute("msg", "旧密码错误");
                }
            }else {
                model.addAttribute("msg", "未登录");
            }
        }else {
            User user = userService.findUserByUserName(userForm.getUsername());
            if(user != null){
                user.setPassword(MD5Util.Md5(userForm.getPasswordNew()));
                if(userService.updateUser(user) == 1){
                    isOK = "OK";
                }else {
                    model.addAttribute("msg", "修改失败");
                }
            }else {
                model.addAttribute("msg", "账号不存在");
            }
        }
        model.addAttribute("isOK", isOK);
        return "";
    }

    /**
     * 登录
     */
    @RequestMapping(value = "/login" , method = RequestMethod.POST)
    public String login(@ModelAttribute()UserForm userForm, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
        String checkCode = (String) WebUtils.getSessionAttribute(request, SESSION_CHECK_CODE);

        if (userForm != null && userForm.getCheckCode() != null && checkCode != null && !"".equals(checkCode)) {
            String inputCheckCode = userForm.getCheckCode().toLowerCase();
            if (inputCheckCode.length() != 4 || !checkCode.equals(inputCheckCode)) {
                model.addAttribute("msg", "验证码错误");
                model.addAttribute("isOK", "NO");
            }else {
                Subject currentUser = SecurityUtils.getSubject();

                String remoteAddr = getRemoteAddr(request);

                ZheUsernamePasswordToken token = new ZheUsernamePasswordToken(userForm.getUsername(), userForm.getPassword(), remoteAddr, userForm.getUserType());

                try {
                    currentUser.login(token);
                    User user = userService.selectByUserName(userForm.getUsername());

                    if (user.getStatus() != 1 && user.getStatus() != 7){
                        model.addAttribute("msg", "用户被锁定,请联系客服!");
                        model.addAttribute("isOK", "NO");
                    }else {
                        writeLog(request, "用户登陆", null, user.getUsername());
                        redirectAttributes.addAttribute("is_login", true);
                        HttpSession session = request.getSession();
                        session.setAttribute("is_login", true);
                        session.setAttribute("login_name", user.getUsername());
                        session.setAttribute("login_id",user.getId());
                        session.setAttribute("login_type",user.getUserType());
                        session.setAttribute("login_province",user.getProvince());
                        session.setAttribute("login_city",user.getCity());
                        session.setAttribute("login_area",user.getArea());

                        model.addAttribute("isOK", "OK");
                    }

                } catch (AuthenticationException ae) {
                    writeLog(request, "登陆失败", "试图使用用户名:" + userForm.getUsername() + "登陆");
                    model.addAttribute("msg", "登录失败，用户名或密码错误!");
                    model.addAttribute("isOK", "NO");
                    logger.info("登陆失败，用户名或密码错误");
                }
            }
        } else {
            model.addAttribute("msg", "数据错误");
            model.addAttribute("isOK", "NO");
        }
        return "";
    }
}
